package org.ccahouse.ccatrain.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.ccahouse.ccacommons.base.BaseController;
import org.ccahouse.ccacommons.common.RestResult;
import org.ccahouse.ccacommons.common.ResultUtils;
import org.ccahouse.ccatrain.annotation.JwtIgnore;
import org.ccahouse.ccatrain.dto.AuthUserDto;
import org.ccahouse.ccatrain.entity.Audience;
import org.ccahouse.ccatrain.service.impl.AuthServiceImpl;
import org.ccahouse.ccatrain.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.HashMap;

@RestController
@RequestMapping(value = "/api/auth")
@Api(tags = "auth模块")
@Validated
public class AuthController extends BaseController {

    @Autowired
    private AuthServiceImpl authService;

    @PostMapping("/register")
    @ApiOperation(value = "注册")
    @JwtIgnore
    @Validated
    public RestResult register(@Validated AuthUserDto authUserDto, BindingResult result) {
        if (result.hasErrors()) {
            FieldError error = result.getFieldError();
            return ResultUtils.error(error.getDefaultMessage());
        }
        return authService.register(authUserDto);
    }

    @PostMapping("/login")
    @ApiOperation(value = "登录")
    @JwtIgnore
    public RestResult login(String username,
                             String password) {
        return authService.login(username, password);
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取userID")
    public RestResult userInfo() {
        Integer userId = JwtTokenUtil.getInstance().getUserId();
        HashMap<String, Integer> map =  new HashMap<>();
        map.put("userId", userId);
        return ResultUtils.success(map);
    }

}
